package com.adtech.adms.systemlog;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;

import com.adtech.adms.Constants;
import com.adtech.adms.commons.util.BeanLoader;
import com.adtech.adms.system.LogConstants;
import com.adtech.core.util.DateUtil;

/**
 * 用户登录日志辅助类
 * 记录系统存活时间，并在系统崩溃重启之后将系统最后存活时间更新到用户登录日志中
 * @author Dormin 
 * @since 2011-6-15 
 * 
 * @Copyright (C) AD Tech Workshop All Right Reserved
 */
public class LoginLogHelper {

	private static Logger log = Logger.getLogger(LoginLogHelper.class);
	private static String separator = ":";
	private static String filePath;

	/**
	 * 
	 * @function 在初始化时更新因系统强制关闭而未更新注销时间的登录日志
	 * @param sc servlet上下文
	 *
	 * @return
	 * @exception
	 *
	 * @author Dormin
	 * @history
	 *
	 */
	public static void init(ServletContext sc){
		Date lastAliveDate = new Date();
		try {
			
			filePath = sc.getRealPath(Constants.KEEP_ALIVE_CONFIG_PATH);
			String aliveStatus = readFromFile();
			if(aliveStatus!=null && aliveStatus.indexOf(separator)!=-1){
				String[] arr = aliveStatus.split(separator);
				if(arr.length>1){
					int status = Integer.parseInt(arr[0]);
					if(status==LogConstants.SYSTEM_RUNNING_STATUS){
						lastAliveDate = DateUtil.string2Date(aliveStatus.substring(2),null);
					}
				}
			}
		} catch (IOException e) {
			log.error(e);
		}  catch (Exception e) {
			log.error(e);
		}
		recordAliveTime();
	//	SystemLogService systemLogService = (SystemLogService) BeanLoader.getBean(sc,Constants.SERVICE_SYSTEM_LOG);
	//	systemLogService.updateInvalidLogoutLog(lastAliveDate);
	}

	/**
	 * 
	 * @function 定时记录系统存活时间
	 * @param
	 *
	 * @return
	 * @exception
	 *
	 * @author Dormin
	 * @history
	 *
	 */
	private static void recordAliveTime() {
		Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable(){
			public void run() {
				try {
					writeToFile(generateLiveMessage());
				} catch (FileNotFoundException e) {
					log.error(e);
				} catch (IOException e) {
					log.error(e);
				}
			}
		}, 0, LogConstants.INTERVAL_KEEP_ALIVE, TimeUnit.SECONDS);
	}

	/**
	 * 
	 * @function 读取文件内容
	 * @param filePath 文件路径
	 *
	 * @return 文件内容
	 * @exception
	 *
	 * @author Dormin
	 * @history
	 *
	 */
	private static String readFromFile() throws IOException {
		File file = new File(filePath);
		if(!file.exists()){
			file.createNewFile();
		}
		BufferedReader reader = null;
		String date = null;
		try{
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			date = reader.readLine();
		} finally {
			if(reader!=null) {
				reader.close();
			}
		}
		return date;
	}

	/**
	 * 
	 * @function  向文件写入内容
	 * @param filePath 文件路径
	 * @param text 需要写入的内容
	 *
	 * @return
	 * @exception
	 *
	 * @author Dormin
	 * @history
	 *
	 */
	private static void writeToFile(String text) throws IOException,
	FileNotFoundException {
		File file = new File(filePath);
		if(!file.exists()){
			file.createNewFile();
		}
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
			writer.write(text);
		} finally {
			if(writer!=null) {
				writer.flush();
				writer.close();
			}
		}
		
	}

	private static String generateLiveMessage(){
		return LogConstants.SYSTEM_RUNNING_STATUS+separator+DateUtil.date2String(new Date(),null);
	}
}
